package ginutil

import (
	"net/http"

	"gitee.com/xuyiping_admin/pkg/jsonpb"
	"gitee.com/xuyiping_admin/pkg/xerr"

	"github.com/gin-gonic/gin"
	"github.com/golang/protobuf/proto"
)

type ProtoMessageQueryBinding struct{}

func BindQueryProto(c *gin.Context, pb proto.Message) error {
	values := c.Request.URL.Query()
	if err := jsonpb.UnmarshalQuery(values, pb); err != nil {
		return xerr.WithStack(err)
	}
	return nil
}

func BindProto(c *gin.Context, pb proto.Message) (err error) {
	switch c.Request.Method {
	case http.MethodGet, http.MethodDelete:
		err = BindQueryProto(c, pb)
	default:
		err = BindProtoMessage(c, pb)
	}
	if err != nil {
		return xerr.WithStack(err)
	}
	return
}
